import React, { FC, useState, useEffect, useRef } from "react";
import QuestionCard from "../../components/QuestionCard";
import { produce } from "immer";
import { Typography, Spin, Empty } from "antd";
import { message } from "antd";
import classNames from "classnames/bind";
import style from "./index.module.scss";
import SearchInput from "../../components/SearchIput";
import { getQuestionList } from "../../service";
import useGetQuestionByKey from "../../hooks/useGetQuestionByKey";
import { SEARCH_PARAMS_PAGE_DEFAULT, SEARCH_PARAMS_KEY } from "../../constant/index";
import { useRequest, useDebounceFn } from "ahooks";
import { useSearchParams } from "react-router-dom";
// import useGetUserDate from "../../hooks/useGetUserDate";
// import useNavPages from "../../hooks/useNavPages";
const { Title } = Typography;
const bindclassNames = classNames.bind(style);
interface questionItem {
  id: string;
  title: string;
  isPublished: boolean;
  isStart: boolean;
  isDelete: boolean;
  answerCount: number;
  createTime: string;
}
type resType = {
  list: questionItem[];
  total: number;
};
const Questionlist: FC = () => {
  // //获取用户信息
  // const { waittingData } = useGetUserDate();
  // //判断登录和未登录跳转判断
  // useNavPages(waittingData);
  const [messageApi, contextHolder] = message.useMessage();
  //获取容器用于监听滚动事件
  const middle = useRef<HTMLDivElement>(null);
  //获取footer组件距离顶部的距离  触发到底部事件
  const foot = useRef<HTMLDivElement>(null);
  //问卷列表数据
  //设置初始数据
  const [listdata, setlistdata] = useState([]);
  //设置初始页面参数
  const [page, setpage] = useState(1);
  const [pageSize, setpageSize] = useState(SEARCH_PARAMS_PAGE_DEFAULT);
  const [total, settotal] = useState(0);
  const hasMoreData = total > listdata.length;
  //获取url路径参数
  const [params] = useSearchParams();
  const keyword = params.get(SEARCH_PARAMS_KEY) || "";

  //底部组件

  const footElected = () => {
    if (loading) return <Spin />;
    if (!hasMoreData) return <span>没有更多拉</span>;
    if (total == 0) return <Empty description="暂时无数据"></Empty>;
    return <span>加载下一页中......</span>;
  };
  //当keyword发生变化的时候，重置参数
  useEffect(() => {
    setlistdata([]);
    settotal(0);
    setpage(1);
  }, [keyword]);
  //当页面初次加载或者url变化的时候
  useEffect(() => {
    load();
  }, [params]);

  //真正的加载
  const { loading, run: load } = useRequest(
    async () => {
      const res = await getQuestionList({
        keyword,
        page,
        pageSize,
      });

      return res;
    },
    {
      manual: true,
      onSuccess(data) {
        const { list = [], total = 0 } = data;
        setlistdata(listdata.concat(list));
        settotal(total);
        setpage(page + 1);
      },
    },
  );

  //滑动到底部触发获取数据的事件 + 防抖
  const { run: tryLoadMore } = useDebounceFn(
    () => {
      const container = middle.current?.parentElement;
      if (!container) return;
      const QuetionList = middle.current;
      // console.log(container?.scrollTop + container?.clientHeight, QuetionList?.clientHeight);
      if (container?.scrollTop + container?.clientHeight >= QuetionList?.clientHeight - 30) {
        if (hasMoreData) {
          load();
        }
      }
    },
    {
      wait: 100,
    },
  );

  //监听向下滑动事件
  useEffect(() => {
    middle.current?.parentNode?.addEventListener("scroll", tryLoadMore);
    //监听销毁事件
    return () => {
      middle.current?.parentNode?.removeEventListener("scroll", tryLoadMore);
    };
  }, [params]);

  //使用自定义hooks
  // const { data = {}, loading } = useGetQuestionByKey({});
  // const { list = [], total = 0 } = data as resType;
  const deletequestionData = (id: string) => {
    // setquestionData(
    //   produce((draft: questionItem[]) => {
    //     const index = draft.findIndex((item: questionItem) => {
    //       return item.id == id;
    //     });
    //     draft.splice(index, 1);
    //     console.log("删除成功");
    //     messageApi.open({
    //       type: "success",
    //       content: "删除成功",
    //     });
    //   }),
    // );
  };

  const publishquestionDate = (id: string) => {
    // setquestionData(
    //   produce((draft: questionItem[]) => {
    //     const index = draft.findIndex((item: questionItem) => {
    //       return item.id == id;
    //     });
    //     draft[index].isPublished = true;
    //   }),
    // );
  };

  const startquestionData = (id: string, flag: boolean) => {
    // setquestionData(
    //   produce((draft: questionItem[]) => {
    //     const index = draft.findIndex((item: questionItem) => {
    //       return item.id == id;
    //     });
    //     draft[index].isStart = flag;
    //   }),
    // );
  };

  return (
    <div className={bindclassNames("QuetionList")} ref={middle}>
      {contextHolder}
      <div className={bindclassNames("head")}>
        <Title level={3} className={bindclassNames("left")}>
          我的问卷
        </Title>
        <div className={bindclassNames("right")}>
          <SearchInput></SearchInput>
          {/* <input className={bindclassNames("searcInput")}></input> */}
        </div>
      </div>
      <div className={bindclassNames("middle")}>
        {listdata.map((item: questionItem) => {
          return (
            <QuestionCard
              {...item}
              key={item.id}
              startquestionData={startquestionData}
              deletequestionData={deletequestionData}
              publishquestionDate={publishquestionDate}
            ></QuestionCard>
          );
        })}
      </div>
      <div className={bindclassNames("foot")}>{footElected()}</div>
    </div>
  );
};

export default Questionlist;
